package com.sfh.cpc.com.widget;

import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sfh.cpc.com.ImageLoaderEngine;
import com.sfh.cpc.com.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述:刷新加载更多控件
 *
 * @date 2017/7/12
 */
public class WidgetMultiSelectPictureLayout extends RecyclerView implements BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {


    /***
     * 点击回调
     */
    public interface OnItemSelectListener {

        /**
         * 选择图片
         */
        void onClickSelect(int size);

        void onClickDel(int position, String data);
    }

    protected int maxSize = 9;

    protected int rowSize;

    // 适配器
    protected DeliverGoodsAdvanceAdapter pullToRefreshAdapter;

    protected OnItemSelectListener listener;

    private int width;

    public List<String> getDataList() {

        // 去除 + 数据
        List<String> data = new ArrayList<>(maxSize);
        for (ImageItem image : pullToRefreshAdapter.getData()) {
            if (!TextUtils.isEmpty(image.url)) {
                data.add(image.url);
            }
        }
        return data;
    }

    public WidgetMultiSelectPictureLayout(@NonNull Context context) {

        super(context);
    }

    public WidgetMultiSelectPictureLayout(@NonNull Context context, @Nullable AttributeSet attrs) {

        super(context, attrs);
    }

    public WidgetMultiSelectPictureLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {

        super(context, attrs, defStyleAttr);
    }


    /***
     *
     * @param maxSize 最大数据
     * @param rowSize 每行数量
     * @param listener
     */
    public void setAdapter(int maxSize, int rowSize, OnItemSelectListener listener) {

        this.maxSize = maxSize;
        this.rowSize = rowSize;
        this.listener = listener;

        this.pullToRefreshAdapter = new DeliverGoodsAdvanceAdapter();
        this.addEmpty(this.pullToRefreshAdapter.getData());
        this.setAdapter(pullToRefreshAdapter);
        this.setLayoutManager(new GridLayoutManager(getContext(), rowSize));
        this.addItemDecoration(new SpaceItemDecoration(this.getResources().getDimensionPixelSize(R.dimen.px_5)));
        this.pullToRefreshAdapter.setOnItemClickListener(this);
        this.pullToRefreshAdapter.setOnItemChildClickListener(this);

    }

    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {

        super.onMeasure(widthSpec, heightSpec);
        width = getMeasuredWidth() / rowSize - 10;
        pullToRefreshAdapter.notifyDataSetChanged();
    }

    /***
     * 1.添加图片
     */
    public void onAdd(String image) {

        List<ImageItem> data =  this.pullToRefreshAdapter.getData();
        //减去最后一条空数据量
        int dataSize = data.size() - 1;
        if (dataSize >= maxSize) {
            return;
        }

        data.remove(ADD);
        data.add(new ImageItem(image));

        // 最多数量
        dataSize = data.size();
        if (dataSize >= maxSize) {
            this.pullToRefreshAdapter.notifyDataSetChanged();
            return;
        }

        this.addEmpty(data);
        this.pullToRefreshAdapter.notifyDataSetChanged();
    }

    /***
     * 1.添加图片
     */
    public void onAdd(List<String> image) {

        List<ImageItem> data =  this.pullToRefreshAdapter.getData();
        // 最后一条数据量
        int dataSize = data.size() - 1;

        if (dataSize >= maxSize) {
            return;
        }

        data.remove(ADD);
        for (String path : image){
            data.add(new ImageItem(path));
        }

        // 最多数量
        dataSize = data.size();
        if (dataSize >= maxSize) {
            this.pullToRefreshAdapter.notifyDataSetChanged();
            return;
        }

        this.addEmpty(data);
        this.pullToRefreshAdapter.notifyDataSetChanged();
    }

    /***
     *   2.删除图片
     */
    public void onDel(int position) {

        List<ImageItem> data =  this.pullToRefreshAdapter.getData();
        final int size = data.size();

        if (position != -1 && position < size) {
            data.remove(position);
        }
        this.addEmpty(data);
        this.pullToRefreshAdapter.notifyDataSetChanged();
    }

    public synchronized void updateStatus(String path,String url){
        List<ImageItem> data =  this.pullToRefreshAdapter.getData();
        for(int i=0; i<data.size();i++){
            if (TextUtils.equals(data.get(i).path,path)){
                data.get(i).url = url;
                data.get(i).fail = TextUtils.isEmpty(url);
                this.pullToRefreshAdapter.notifyItemChanged(i);
                break;
            }
        }
    }
    private void addEmpty(List<ImageItem> data) {

        final int size = data.size();
        if (size == 0) {
            data.add(ADD);
            return;
        }

        final int lastIndex = size - 1;
        ImageItem lastData = pullToRefreshAdapter.getItem(lastIndex);
        // 最后一个是空数据
        if (ADD.equals(lastData)) {
            return;
        }

        if (size < maxSize) {
            data.add(ADD);
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

        if (listener == null) {
            return;
        }
        ImageItem mData = (ImageItem) adapter.getItem(position);
        if (ADD.equals(mData)) {
            // 添加图片
            int size = maxSize - adapter.getData().size() + 1;
            listener.onClickSelect(size);
        }

    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

        if (listener == null) {
            return;
        }
        //删除
        ImageItem mData = (ImageItem) adapter.getItem(position);
        listener.onClickDel(position, mData.path);
    }

    private ImageItem ADD = new ImageItem("-1");

    class ImageItem {

        public ImageItem(String path) {
            this.path = path;
            this.pathFile = new File(path);
        }

        public String path;
        public String url;
        public boolean fail;
        public File pathFile;
        @Override
        public boolean equals(Object obj) {
            return TextUtils.equals(path, ((ImageItem) obj).path);
        }
    }


    class DeliverGoodsAdvanceAdapter extends BaseQuickAdapter<ImageItem, BaseViewHolder> {

        public DeliverGoodsAdvanceAdapter() {

            super(R.layout.widget_multi_select_item);
        }


        @Override
        protected void convert(BaseViewHolder helper, ImageItem item) {

            ImageView iv = helper.getView(R.id.ivItem);

            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) iv.getLayoutParams();
            params.rightMargin = 15;
            params.topMargin = 15;
            params.width = width - 15;
            params.height = width - 15;
            params.gravity = Gravity.CENTER;
            iv.setLayoutParams(params);

            // 删除
            helper.addOnClickListener(R.id.ivOption);

            if (ADD.equals(item) || TextUtils.isEmpty(item.path)) {
                // 添加图片
                helper.setVisible(R.id.iv_fail, false).setVisible(R.id.ivOption, false).setVisible(R.id.progressBar, false);
                iv.setImageResource(R.drawable.bg_add_photo);
            } else {
                helper.setVisible(R.id.ivOption, true);
                new ImageLoaderEngine(iv,  item.pathFile).resizeDimen(R.dimen.px_90, R.dimen.px_90).centerCrop().into(iv);

                if (TextUtils.isEmpty(item.url)) {
                    if (item.fail) {
                        // 上传失败
                        helper.setVisible(R.id.iv_fail, true).setVisible(R.id.progressBar, false);
                    } else {
                        //正在上传
                        helper.setVisible(R.id.iv_fail, false).setVisible(R.id.progressBar, true);
                    }

                } else {
                    helper.setVisible(R.id.iv_fail, false).setVisible(R.id.progressBar, false);
                }
            }

        }
    }


    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            //不是第一个的格子都设一个左边和底部的间距
            outRect.left = space;
            outRect.bottom = space;

            int size = parent.getChildLayoutPosition(view);

            RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
            if (layoutManager instanceof GridLayoutManager) {
                //每行数量
                int spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
                //由于每行第一个，所以第一个都是每行数量的倍数，把左边距设为0
                if (size % spanCount == 0) {
                    outRect.left = 0;
                }
            } else {
                outRect.left = 0;
            }
        }

    }
}
